<template>
  <div>
    <div className="hello">
      <TimePickerRain
          @time-range-selected="handleTimeSelected"
      ></TimePickerRain>
      <div style="height: 10px">
        <strong style="display: block; text-align: center; font-size: 40px"
        >降水</strong
        >
      </div>
      <div className="box">
        <div className="chart">
          <div id="charts" ref="chart"></div>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {onMounted, onUnmounted, reactive, ref} from "vue";
import 'echarts-gl';
import 'echarts/map/js/province/guangdong.js';
import geoJson from '../assets/yuegangao.json';
import regionStylesData from '../assets/regionStyles.json';
import 'echarts-extension-amap';
import {useStore} from 'vuex'; // 引入useStore 方法
import {getPrecipitationData} from '@/api/user/rainfall';
import TimePickerRain from './TimePickerRain'

export default {
  name: "rainfall",

  components: {
    TimePickerRain,
  },

  setup() {

    const store = useStore()  // 该方法用于返回store 实例
    let myEcharts = echarts;
    let chart = null;
    let object = {
      user_id: store.state.userinfo.id,
      nums: 10
    }

    let arrayData = reactive({
      arrData: []
    });
    let cooData = ref([])

    let params = {
      year: 2023,
      month: 4,
      day: 26,
      hour: 6,
      minute: 18,
      predict: 6
    };


    function handleTimeSelected(selectedTime) {
      console.log("time", selectedTime);
      const {date, start, predict} = selectedTime;
      // 分割日期和时间
      const [year, month, day] = date.split('-');
      const [hours, minutes] = start.split(':');
      params.year = year;
      params.month = month;
      params.day = day;
      params.hour = hours;
      params.minute = minutes;
      params.predict = predict; // 设置新的预测时间
      console.log('params.predict:', params.predict);
      console.log('params.day:', params.day);
      initChart();
    }


    onMounted(() => {
      initChart();
    });
    onUnmounted(() => {
      myEcharts.dispose;
      chart.dispose();
      chart = null;
    });

    async function initChart() {

      let COLORS = ['#FFFFFF', '#b1f79f', '#4bb845', '#65b7f1', '#0306f5', '#f702f3', '#71093e']

      let StartLat = 27.0
      let StartLon = 108.5
      let XReso = 0.01
      let YReso = 0.01

      cooData = await fetchCOOData(params);
      console.log(cooData)
      arrayData.arrData = await updateArrayData()

      let data = []
      for (const item of arrayData.arrData) {
        const lon = StartLon + item[1] * XReso
        const lat = StartLat - item[0] * YReso
        data.push([lon, lat, item[2]])
      }

      const guangdongCenter = [113.280637, 23.125178];
      chart = myEcharts.init(document.getElementById("charts"), "purple-passion");
      // 注册可用的地图
      myEcharts.registerMap('guangdong', geoJson);
      // 设置echarts的option
      await loadRegionStyles(chart);//突出大湾区线条
      chart.setOption({
        title: {
          x: 'center'
        },
        tooltip: {},
        visualMap: {
          type: 'piecewise',
          inverse: true,
          bottom: '2%',
          right: '1%',
          pieces: [
            {
              min: 0,
              max: 1,
              color: COLORS[1],
              // opacity: 0
            },
            {
              min: 1,
              max: 10,
              color: COLORS[2]
            },
            {
              min: 10,
              max: 25,
              color: COLORS[3]
            },
            {
              min: 25,
              max: 50,
              color: COLORS[5]
            },
            {
              min: 50,
              // max: 100,
              color: COLORS[6]
            },
          ],
          borderColor: '#ccc',
          borderWidth: 2,
          backgroundColor: '#eee',
          // dimension: 2,
          inRange: {
            color: COLORS,
            opacity: 0.7
          }
        },
        geo: {
          map: 'guangdong',
          center: guangdongCenter,//地图中心
          aspectScale: 1, //长宽比
          zoom: 7,
          roam: true,
          itemStyle: {
            normal: {
              borderColor: '#f4f4f4',
              areaColor: '#fff',
              shadowColor: '#182f68',
              shadowOffsetX: 0,
              shadowOffsetY: 1,
            },
            emphasis: {
              areaColor: '#fff',
              borderWidth: 0,
              label: {
                show: false
              }
            }
          },
          scaleLimit: {
            min: 5,                          //最小的缩放值
            max: 30,                            //最大的缩放值
          }
        },
        series: [
          {
            type: 'scatter',
            symbol: 'rect',
            symbolSize: 5,
            coordinateSystem: 'geo',
            animation: false,
            large: true,
            largeThreshold: 5000000,
            emphasis: {//强调
              itemStyle: {
                color: 'blue'
              }
            },
            encode: {
              tooltip: 2
            },
            data: data
          },
        ],
      });
      window.onresize = function () {
        chart.resize();
      };
    }

    async function loadRegionStyles(chart) {
      try {
        // 使用导入的 JSON 数据
        const regionStyles = regionStylesData;
        chart.setOption({
          geo: {
            regions: regionStyles.regions,
          },
        });
      } catch (error) {
        console.error('Error loading region styles:', error);
      }
    }

    async function fetchCOOData(params) {
      try {
        let cooData1 = await getPrecipitationData(params); // 使用接口文件中的函数获取数据
        return cooData1
      } catch (error) {
        console.error('Error fetching COO data:', error);
      }
    }

    async function updateArrayData() {
      let array = cooData.map(item => item.coo);
      return array[0]
    }

    return {
      arrayData,
      cooData,
      handleTimeSelected
    }
  }
}
</script>

<style scoped lang="scss">
.head-name {
  color: #b0e3ff;
  font-weight: bold;
  font-size: xx-large;
  padding: 50px;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
}


@media screen and (min-width: 700px) {
  .chart {
    border: 3px double #c7e8ff;
    background-color: #6c8fff;
    margin: 60px;
    width: 70%;
    height: 65vh;

    #charts {
      width: 100%;
      height: 65vh
    }
  }
}


</style>
